from flask import Flask, render_template, request,jsonify,escape
from panduan import panduan_login
from pymysql import connect
from geo import geocode,integrated,weather,around
import pyecharts.options as opts
from pyecharts.charts import Line


# 连接数据库函数
def look_over():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="travel")
	cursor1 = con.cursor()
	sql = "select * from useradmin"
	cursor1.execute(sql)
	res = cursor1.fetchall()
	print(res)
	return res

def log_request(req:"flask_request",res:str):
	with open('vsearch.log','a') as log:
		print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')


app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('first.html')


# 网站首页
@app.route('/entry')
def first() -> 'html':
	return render_template('entry.html')  


# 注册界面
@app.route('/regist')
def regist_page() -> 'html':
	return render_template('regist.html',the_title ="注册！")    


@app.route('/addregist',methods=['POST'])
def regist() -> 'html':
	username = request.form["inputUsername"]
	password = request.form["inputPassword"]
	print(username,password)
	con = connect(host="localhost",port=3306,user="root",password="123456",db="travel")
	cursor3 = con.cursor()
	# 将用户输入的信息传入数据库
	sql = "insert into useradmin set username='%s',password='%s'"%(username,password)
	cursor3.execute(sql)
	con.commit()
	return render_template('rsucess.html')


# 渲染修改界面
@app.route("/modify1")
def modify_page():
	return render_template("modify.html")


@app.route("/modify",methods=["POST"])
def modify():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="travel")
	cursor5 = con.cursor()
	username = request.form.get("username")
	password = request.form.get("password")
	# 将用户修改的password更新至数据库
	sql = "update useradmin set password='%s' where username='%s'"% (password,username)
	cursor5.execute(sql)
	res= cursor5.fetchall()
	con.commit()
	return render_template("modifysucess.html",username=username,password=password)


# 注销用户界面
@app.route('/delect')
def delete_page() -> 'html':
	return render_template('delect.html')


@app.route("/delectsucess",methods=["POST"])
def delect():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="travel")
	cursor6 = con.cursor()
	username = request.form.get("username")
	password = request.form.get("password")
	# 将用户要注销的账户对应删除数据库的值
	sql = "delete from useradmin where username='%s'"% (username)
	cursor6.execute(sql)
	res= cursor6.fetchall()
	con.commit()
	return render_template("delectsucess.html",username=username,password=password)


# 登入界面
@app.route('/login')
def login_page() -> 'html':
	return render_template('login.html',the_title ="欢迎您登录GO官网！")


@app.route('/addlogin',methods=['POST'])
def login():
	username = request.form["inputUsername"]
	password = request.form["inputPassword"]
	a = panduan_login(username, password)
	# 判断用户所输入的信息是否正确
	con = connect(host="localhost",port=3306,user="root",password="123456",db="travel")
	cursor7 = con.cursor()
	sql = 'select * from traveling'
	cursor7.execute(sql)
	res = cursor7.fetchall()
	log_request(request,a)
	if a == "true":
		return render_template('search.html',the_title ="登录成功，欢迎您进入GO官网！",the_data=res)
	else:
		return "登入失败。登入失败原因可能为数据库数据传值有延时/用户名/密码输入错误,进入..../login页面重新登入可用账户chenxi,密码123456"


# 日志系统
@app.route('/viewlog')
def view_the_log() -> 'html':
	# 以读的方式打开文件
	with open("vsearch.log","r") as log:
		contents =[]
		for line in log:
			contents.append([])
			for item in line.split("|"):
				contents[-1].append(escape(item))
	title= ['Form data','Remote_addr','User_agent','Results']
	return render_template("view.html",the_title=title, the_data =contents)


@app.route('/search',methods = ['POST'])
def search_sight() -> 'html':
	con = connect(host="localhost",port=3306,user="root",password="123456",db="travel")
	cursor5 = con.cursor()
	# 获取用户输入的地区信息
	district = request.form["district"]
	# 筛选地区的景点，当district不为空时，查询数据库里相对应的景点
	if district !='':
		sql = "select * from traveling where district = '%s'"%(district)
	else:
		sql = 'select * from traveling'
	cursor5.execute(sql)
	res = cursor5.fetchall()
	print(res)
	return render_template("search.html", the_data=res)


@app.route('/go')
def how() -> 'html':
	return render_template("go.html")


@app.route('/howtogo',methods=['post'])
def howgo() -> 'html':
	district = request.form["district"]
	a = weather(district)
	# 遍历循环结果，将所需值添加进相对应的空列表中
	date=[]
	for i in a['forecasts'][0]['casts']:
		date.append(i['date'])
	daytemp=[]
	for i in a['forecasts'][0]['casts']:
		daytemp.append(i['daytemp'])
	nighttemp=[]
	for i in a['forecasts'][0]['casts']:
		nighttemp.append(i['nighttemp'])


	# pyecharts绘制折线图
	(
	    Line(init_opts=opts.InitOpts(width="1600px", height="800px"))
	    .add_xaxis(xaxis_data=date)
	    .add_yaxis(
	        series_name="日间气温",
	        y_axis=daytemp,
	        markpoint_opts=opts.MarkPointOpts(
	            data=[
	                opts.MarkPointItem(type_="max", name="最大值"),
	                opts.MarkPointItem(type_="min", name="最小值"),
	            ]
	        ),
	        markline_opts=opts.MarkLineOpts(
	            data=[opts.MarkLineItem(type_="average", name="平均值")]
	        ),
	    )
	    .add_yaxis(
	        series_name="夜间气温",
	        y_axis=nighttemp,
	        markpoint_opts=opts.MarkPointOpts(
	            data=[opts.MarkPointItem(value=-2, name="周最低", x=1, y=-1.5)]
	        ),
	        markline_opts=opts.MarkLineOpts(
	            data=[
	                opts.MarkLineItem(type_="average", name="平均值"),
	                opts.MarkLineItem(symbol="none", x="90%", y="max"),
	                opts.MarkLineItem(symbol="circle", type_="max", name="最高点"),
	            ]
	        ),
	    )
	    .set_global_opts(
	        title_opts=opts.TitleOpts(title="近4日昼夜气温变化"),
	        tooltip_opts=opts.TooltipOpts(trigger="axis"),
	        toolbox_opts=opts.ToolboxOpts(is_show=True),
	        xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
	    )
	    .render("templates/temp_change_line_chart.html")
	)


	province = a['forecasts'][0]['province']
	city = a['forecasts'][0]['city']
	dayweather0 = a['forecasts'][0]['casts'][0]['dayweather']
	daytemp0 = a['forecasts'][0]['casts'][0]['daytemp']
	daywind0 = a['forecasts'][0]['casts'][0]['daywind']
	dayweather1 = a['forecasts'][0]['casts'][1]['dayweather']
	dayweather2 = a['forecasts'][0]['casts'][2]['dayweather']
	dayweather3 = a['forecasts'][0]['casts'][3]['dayweather']
	return render_template("how_to_go.html",province = province,city = city,
		district=district,dayweather0=dayweather0,dayweather1=dayweather1,
		dayweather2=dayweather2,dayweather3=dayweather3, daytemp0=daytemp0, daywind0=daywind0,)

# 渲染折线图html
@app.route('/tempchange')
def temp() -> 'html':
	return render_template("temp_change_line_chart.html")

@app.route('/around')
def around0() -> 'html':
	return render_template("around.html")

#周边搜索
@app.route('/places',methods=['post'])
def placesa() -> 'html':
	location = request.form["location"]
	keywords = request.form["keywords"]
	a = geocode(location)
	b = around(a,keywords)
	
	# 遍历循环结果，将所需值添加进相对应的空列表中
	address = []
	name = []
	for i in b:
		address.append(i['address'])
		print(address)
	for i in b:
		name.append(i['name'])
	combine = dict(zip(name,address))
	return render_template("places.html",the_data = combine,res=address)


if __name__ == '__main__':
    app.run(debug=True)